// EpollServer.hpp
#pragma once
#include "TcpSocket.hpp"
#include "Epoller.hpp"
#include <memory>

static const uint16_t defaultport = 8080;

uint32_t EVENT_IN = {EPOLLIN};
uint32_t EVENT_OUT = {EPOLLOUT};

class EpollServer : public nocopy
{
    static const int num = 64;

public:
    EpollServer(uint16_t port = defaultport)
        : _port(port), _listensock_ptr(new TcpSocket), _epoller_ptr(new Epoller)
    {
    }
    ~EpollServer()
    {
        _listensock_ptr->Close();
    }
    void Init()
    {
        _listensock_ptr->Socket();
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();

        lg(Info, "create listen socker success, fd: %d", _listensock_ptr->getfd());
    }
    void Start()
    {
        // 将listensock添加到epoll中 -> 将listensock和它关心的事件添加到内核epoll模型中的rb_tree中
        _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, _listensock_ptr->getfd(), EVENT_IN);

        struct epoll_event revs[num];
        for (;;)
        {
            int n = _epoller_ptr->EpollerWait(revs, num);
            if (n > 0)
            {
                // 有事件就绪
                lg(Debug, "event happened, fd is %d", revs[0].data.fd);
                Dispatcher(revs, n);
            }
            else if (n == 0)
            {
                lg(Info, "time out...");
            }
            else
            {
                lg(Error, "epoll wait error");
            }
        }
    }
    void Dispatcher(struct epoll_event *revs, int num)
    {
        for (int i = 0; i < num; ++i)
        {
            uint32_t events = revs[i].events;
            int fd = revs[i].data.fd;
            if (events & EVENT_IN)
            {
                if (fd == _listensock_ptr->getfd())
                {
                    // 获取了一个新连接
                    Accepter();
                }
                else
                {
                    // 普通fd读事件就绪
                    Recver(fd);
                }
            }
            else if (events & EVENT_OUT)
            {
            }
            else
            {
            }
        }
    }
    void Accepter()
    {
        std::string clientip;
        uint16_t clientport;
        int sockfd = _listensock_ptr->Accept(&clientip, &clientport);
        if (sockfd > 0)
        {
            // 连接建立好了，但对方不一定发了数据，所以不能直接read，而是交给epoll
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, sockfd, EVENT_IN);
            lg(Info, "get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }
    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); // bug: 无法保证读上来的是一个完整的报文
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;

            // write
            std::string echo_str = "server echo$ ";
            echo_str += buffer;
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            // 对方把文件描述符关了，我这边读到了结尾，所以要在epoll中移除fd，并关闭fd
            // 注意，一定要先移除，后close，不然epoll就会报错，因为fd已经不存在了
            lg(Info, "client quit, me too. close fd %d", fd);
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            // 读出错
            lg(Warning, "recv error, close fd %d", fd);
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

private:
    std::shared_ptr<TcpSocket> _listensock_ptr;
    std::shared_ptr<Epoller> _epoller_ptr;
    // TcpSocket _listensock;
    // Epoller _epoller;
    uint16_t _port;
};